<?php
// .-----------------------------------------------------------------------------------
// | WE TRY THE BEST WAY
// |-----------------------------------------------------------------------------------
// | Author: 贝贝 <hebiduhebi@163.com>
// | Copyright (c) 2013-2015, http://www.gooraye.net. All Rights Reserved.
// |-----------------------------------------------------------------------------------

namespace app\admin\api;

use app\common\api\BaseApi;
use app\admin\model\ViewPage;
use app\admin\model\ViewPageItem;
use app\shop\model\ProductGroup;
use app\shop\api\ProductApi;
use app\shop\api\ProductSkuApi;

class ViewPageApi extends BaseApi{

    /**
     * 添加
     */
    const ADD = "admin/ViewPageApi/add";
    /**
     * 保存
     */
    const SAVE = "admin/ViewPageApi/save";
    /**
     * 保存根据ID主键
     */
    const SAVE_BY_ID = "admin/ViewPageApi/saveByID";

    /**
     * 删除
     */
    const DELETE = "admin/ViewPageApi/delete";

    /**
     * 查询
     */
    const QUERY = "admin/ViewPageApi/query";

    /**
     * 查询不分页
     */
    const QUERY_NO_PAGING = "admin/ViewPageApi/queryNoPaging";

    /**
     * 查询一条数据
     */
    const GET_INFO = "admin/ViewPageApi/getInfo";

    /**
     * 获取page数据,只取第一条记录
     */
    const GET_PAGE_INFO = "admin/ViewPageApi/getPageInfo";

    /**
     * 保存page数据
     */
    const SAVE_PAGE_INFO = "admin/ViewPageApi/savePageInfo";

    /**
     * 删除page
     */
    const DELETE_PAGE = "admin/ViewPageApi/deletePage";
    const QUERY_PAGE  = "admin/ViewPageApi/pageAppQuery";

	protected function _init(){
		$this->model = new ViewPage();
	}
    /**
     * 获取APP页面ids
     */
    public function pageAppQuery(){
        $pages = [];
        $pages['cate'][] = ['name'=>'首页','page_id'=>1]; //app首页
        $model = $this->model;
        $result = $model->where(['notes'=>'APP分类布局'])->select();
        if(false === $result) return $this->apiReturnErr($model->getDbError());
        foreach($result as $val){
            $pages['cate'][] = ['name'=>$val['name'],'page_id'=>$val['id']];
        }
        $result = $model->where(['notes'=>'APP地区分类布局'])->select();
        if(false === $result) return $this->apiReturnErr($model->getDbError());
        foreach($result as $val){
            $pages['cate_global'][] = ['name'=>$val['name'],'page_id'=>$val['id']];
        }
        $result = $model->where(['notes'=>'APP其他分类布局'])->select();
        if(false === $result) return $this->apiReturnErr($model->getDbError());
        foreach($result as $val){
            $pages['cate_other'][] = ['name'=>$val['name'],'page_id'=>$val['id']];
        }
        return $this->apiReturnSuc($pages);
    }

    /**
     * 获取page数据,只取第一条记录
     */
    public function getPageInfo($map){
        $model  = $this->model;
        $result = $model->where($map)->find();
        if(false === $result) return $this->apiReturnErr($model->getDbError());
        //查询pageItem
        // if(empty($result)){
        //     return $this->apiReturnSuc(null);
        // }
        // trace('===');
        // trace($result);
        // return  $this->apiReturnSuc($result);

        $pageInfo   = $result;
        $page_id    = $result['id'];
        $item_model = new ViewPageItem();
        $map    = ['page_id'=>$page_id];
        $result = $item_model->where($map)->order(['display_order'=>'desc'])->select();
        if(false === $result) return $this->apiReturnErr($model->getDbError());
        foreach($result as &$val){
            $data = json_decode($val['data'],true);
            foreach($data['banners'] as &$v){
                if(isset($v['product_home'])){
                    $v['product_home']['product_info'] = $this->queryProductInfo($v['product_home']['product_ids']);
                }
            }

            $val['data'] = json_encode($data);
        }

        $pageInfo['item_data'] = $result;

        return $this->apiReturnSuc($pageInfo);
    }

    /**
     * 保存page数据,
     */
	public function savePageInfo($pageInfo){

        /*let pageData = [
            {
                block_id : 1,
                item_name: '首页四格'
                banners: [
                    {key:1 ,id:0, name:'保税区',width:150, height:150,
                        group_product_list :{
                        p_ids: [],
                            sku: {
                        }
                        }
                    },
                    {key:2, id:0, name:'搭配购',width:150, height:150,
                        group_product_list :{
                        p_ids: [],
                            sku: {
                        }
                        }
                    },
                    {key:3, id:0, name:'特卖汇',width:150, height:150,
                        group_product_list :{
                        p_ids: [],
                            sku: {
                        }
                        }
                    },
                    {key:4, id:0, name:'限量购',width:150, height:150,
                        group_product_list :{
                        p_ids: [],
                            sku: {
                        }
                        }
                    }
                ]
            }
        ];*/

        $page_data = $pageInfo['page_data'];
        $page_id = $pageInfo['page_id'];

        $map = ['id'=>$page_id];
        $model = $this->model;
        $result = $model->where($map)->find();
        if($result===false){
            $error = $model->getDbError();
            return $this->apiReturnErr($error);
        }

        //查询pageItem
        if(is_null($result)){
            return $this->apiReturnErr('保存失败,指定page不存在');
        }

        $item_model = new ViewPageItemModel();
        $item_model->startTrans();
        $flag = true;

        foreach($page_data as $val){

            $data = [
                'page_id' => $page_id,
                'item_name' => $val['block_name'],
                'dt_item_type' => 0,
                'data' => json_encode($val)
            ];
            $map = [
                'id'=>$val['block_id'],
                'page_id' => $page_id
            ];

            $result = $item_model->where($map)->save($data);
            if($result===false){
                $flag = false;
                break;
            }else{
                $result = $item_model->where($map)->count();
                if($result==0){
                    $result = $item_model->add($data);
                    if($result===false){
                        $flag = false;
                        break;
                    }
                }
            }

        }
        if($flag){
            $item_model->commit();
            return $this->apiReturnSuc('保存成功');
        }else{
            $item_model->rollback();
            return $this->apiReturnErr('保存失败');
        }

    }

    /**
     * 根据page_sku保存添加商品分组
     */
    public function saveGroupSku($sku_list,$g_id){
        $model = new ProductGroupModel();
        $model->startTrans();
        $flag = true;
        if(count($sku_list)==0){
            return $this->apiReturnSuc('保存成功');
        }
        foreach($sku_list as $key=>$val){
            if($val==null){
                continue;
            }
            $result = $model->where(['p_id'=>$key,'g_id'=>$g_id])->delete();
            if($result===false){
                $flag = false;
                break;
            }
            $dataList = [];
            foreach($val as $v2){
                $dataList[] = [
                    'sku_id'=>$v2['sku_id'],
                    'g_id'=>$g_id,
                    'start_time'=>$v2['start_time'],
                    'end_time'=>$v2['end_time'],
                    'price'=>$v2['price'],
                    'display_order'=>$v2['display_order']
                ];
            }
            $result = $model->addAll($dataList);
            if($result===false){
                $flag = false;
                break;
            }
        }
        if($flag){
            $model->commit();
            return $this->apiReturnSuc('保存成功');
        }else{
            $model->rollback();
            $error = $model->getDbError();
            return $this->apiReturnErr($error);
        }
    }

    /**
     * 删除page,只删除第一条
     */
    public function deletePage($map){

        $model = $this->model;
        $flag = true;
        $model->startTrans();

        $result = $model->where($map)->find();
        if($result===false){
            $flag=false;
        }else{
            if(!is_null($result)){
                $page_id = $result['id'];
                //删除page
                $result = $model->where(['id'=>$page_id])->delete();
                if($result===false){
                    $flag=false;
                }else{
                    //删除pageItem
                    $itemModel = new ViewPageItemModel();
                    $result = $itemModel->where(['page_id'=>$page_id])->delete();
                    if($result===false){
                        $flag=false;
                    }
                }
            }
        }
        if($flag){
            $model->commit();
            return $this->apiReturnSuc('删除成功');
        }else{
            $model->rollback();
            $error = $model->getDbError();
            return $this->apiReturnErr($error);
        }
    }


    private function queryProductInfo($ids){
        if(empty($ids)) return [];
        $map['_string'] = '`pro`.`id` in ('.implode(',', $ids).')';
        $field = ['product_id','name','image.img_id as img','price'];
        $page  = ['curpage'=>1,'size'=>100];
        $result = apiCall(ProductApi::QUERY_WITH_COUNT,[$map,$page,'`pro`.`id` asc',false,$field]);
        if($result['status']){
            $list = $result['info']['list'];
            //查询最小价格 - 会员价中
            foreach ($list as &$v) {
                $r = (new ProductSkuApi())->getMinPriceByPid($v['product_id']);
                if($r['status'] && $r['info']){
                    $v['price'] = $r['info'];
                }
            }
            return $list;
            // $data = [];
            // foreach($ids as $val){
            //     foreach($list as $val2){
            //         if($val2['product_id']==$val){
            //             $data[] = $val2;
            //         }
            //     }
            // }
            // return $data;
        }else{
            return [];
        }

    }
}